package vn.edu.thptduongbachmai.common;

import com.vng.zing.logger.ZLogger;
import vn.edu.thptduongbachmai.model.pojo.Users;
import vn.edu.thptduongbachmai.services.SessionService;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;

/**
 *
 * @author tiennv4
 */
public class Auth {

	private static final Logger _Logger = ZLogger.getLogger(Auth.class);
	public static final String AUTH_KEY = Configuration.APP_KEY_COOKIE;
	private String userName;
	private long userId;
	private boolean isLogged;

	public Auth() {
		this.userId = -1;
		this.userName = "";
		this.isLogged = false;
	}
	
		public Auth(Users user) {
		userName = user.getUsername();
		userId = user.getId();
		isLogged = true;
	}


	public void reset(Auth auth) {
		userName = auth.userName;
		userId = auth.userId;
		isLogged = auth.isLogged;
	}

	public String getUserName() {
		return userName;
	}

	public String getUserName(String def) {
		if (userName != null) {
			return userName;
		}
		return def;
	}

	public long getUserId() {
		return userId;
	}

	public boolean isLogged() {
		return isLogged;
	}


	public static Auth getIdentity(HttpServletRequest req) {
		String sessionId = "";
		Auth auth = new Auth();
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(AUTH_KEY)) {
					sessionId = cookie.getValue();
					break;
				}
			}
			if (!sessionId.isEmpty()) {
				try {
					auth.reset((Auth) SessionService.Instance.get(sessionId));
				} catch (Exception ex) {
					_Logger.error(ex.getMessage(), ex);
				}
			}
		}
		req.setAttribute(AUTH_KEY, auth);
		return auth;
	}

	public static boolean logout(HttpServletRequest req, HttpServletResponse resp) {
		String sessionId = "";
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(AUTH_KEY)) {
					sessionId = cookie.getValue();
					cookie.setPath("/");
					cookie.setMaxAge(0);
					cookie.setVersion(1);
					resp.addCookie(cookie);
					break;
				}
			}
			if (!sessionId.isEmpty()) {
				try {
					boolean session = SessionService.Instance.remove(sessionId);
					if (session) {
						return true;
					}
				} catch (Exception ex) {
					_Logger.error(ex.getMessage(), ex);
				}
			}
		}
		return false;
	}

	public static void createCookie(String session, HttpServletResponse resp) {
		Cookie cookie = new Cookie(AUTH_KEY, session);
		cookie.setMaxAge(60 * 60 * 6);
		cookie.setVersion(1);
		resp.addCookie(cookie);
	}

	public static void createCookie(String session, String domain, HttpServletResponse resp) {
		Cookie cookie = new Cookie(AUTH_KEY, session);
		cookie.setMaxAge(60 * 60 * 6);
		cookie.setDomain(domain);
		cookie.setPath("/");
		cookie.setVersion(1);
		resp.addCookie(cookie);
	}

	public static void createCookie(String cookieName, String value, String domain, HttpServletResponse resp) {
		Cookie cookie = new Cookie(cookieName, value);
		cookie.setMaxAge(60 * 60 * 6);
		cookie.setDomain(domain);
		cookie.setPath("/");
		cookie.setVersion(1);
		resp.addCookie(cookie);
	}

	public static String getCookie(String cookieName, HttpServletRequest req) {
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(cookieName)) {
					return cookie.getValue();
				}
			}
		}
		return "";
	}
	
		@Override
	public String toString() {
		JSONObject json = new JSONObject();
		json.put("userName", userName);
		json.put("userId", userId);
		json.put("isLogged", isLogged);
		return json.toJSONString();
	}

	public JSONObject toJSONObject() {
		JSONObject json = new JSONObject();
		json.put("userName", userName);
		json.put("userId", userId);
		json.put("isLogged", isLogged);
		return json;
	}
}
